package zl.osimall.front.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zl.osimall.common.bean.Cart;
import zl.osimall.common.bean.RespBean;
import zl.osimall.common.bean.User;
import zl.osimall.common.exception.SteduException;
import zl.osimall.common.service.CartService;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @GetMapping
    public  String toCart(){
        return "/user/cart";
    }

    @GetMapping("/add")
    public String add(Integer goodsId, HttpSession session, Model m){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();
        Cart cart = new Cart();
        cart.setGoodsId(goodsId);
        cart.setUserId(userId);
        try {
            cartService.add(cart);
            return "user/cart";
        } catch (SteduException e) {
            e.printStackTrace();
            m.addAttribute("errMsg", e.getMessage());
            return "user/error";
        }
    }

    @GetMapping("/getAll")
    @ResponseBody
    public RespBean selectByUserId(HttpSession session){
        User user = (User) session.getAttribute("user");
        Integer userId = user.getId();
        List<Cart> cartList = cartService.selectByUserId(userId);
        return RespBean.ok("查询成功",cartList);
    }

    @GetMapping("/update")
    @ResponseBody
    public RespBean update(Integer cartId, Integer count,HttpSession session){
        User user = (User)session.getAttribute("user");
        Integer userId = user.getId();
        try {
            cartService.update(cartId, count, userId);
            return RespBean.ok();
        } catch (SteduException e) {
            e.printStackTrace();
            return RespBean.error(e.getMessage());
        }
    }

    @GetMapping("/delete")
    @ResponseBody
    public RespBean delete(Integer cartId, HttpSession session){
        User user = (User)session.getAttribute("user");
        Integer userId = user.getId();
        try {
            cartService.delete(cartId, userId);
            return RespBean.ok();
        } catch (SteduException e) {
            e.printStackTrace();
            return RespBean.error(e.getMessage());
        }
    }

}
